<template>
  <div class="weekly-report-form">
    <div class="person" >
      <div style="display:inline-block">
        <span>账户：</span>
        <i class="el-icon-user icon"></i>
        <span @click="handleDialogSelectUser" style="color: #409EFF">{{ selectedUser.username }}</span>
      </div>
      <div style="display:inline-block">
        <span style="color:red">
          填报人：　<el-input size="small" class="top-input" list="tbr" @input="handChangeTbr" v-model="tbr"/>
          <datalist id="tbr">
            <option
              v-for="(item, index) in dataListForTbr"
              :value="item"
              :key="index"
            ></option>
          </datalist>
        </span>
        <span style="color:red">
          联系方式：<el-input size="small" class="top-input" list="tbrPhone" @input="handChangePhone" v-model="tbrPhone"/>
          <datalist id="tbrPhone">
            <option
              v-for="(item, index) in dataListForTbrPhone"
              :value="item"
              :key="index"
            ></option>
          </datalist>
        </span>
      </div>
    </div>
    <!-- 暂时隐藏 随机抽查参数 -->
    <!-- <div v-if="isSpecialLeader" class="person">
      <span>随机抽查：</span>
      <el-switch v-model="isRandomCheck" :active-value="1" :inactive-value="0"/>
    </div> -->
    <el-row :gutter="20" v-if="planType === '月'">
      <el-col :sm="24" :md="6" :lg="6" style="margin-bottom: 10px;">
        <current-month-week-plan :selectedUserId="selectedUser.user" :date="date"/>
      </el-col>
      <el-col :sm="24" :md="18">
        <el-card class="box-card">
          <div class="header">
            <h2>{{ tableTitle }}</h2>
            <div class="extra">
              <span>单位（职务）：</span>
              <span
                >填表日期：{{ parseTime(new Date(), "{y}年{m}月{d}日") }}</span
              >
            </div>
          </div>
          <weekly-report-table
            :dataSource="weeklyReportDatas"
            :planType="planType"
            :columnNames="columnNames"
            :onAdd="handleAddRecord"
            :onDelete="handleDeleteRecord"
            :onSubmit="handleSaveRecord"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-card v-else class="box-card">
          <div class="header">
            <h2>{{ tableTitle }}</h2>
            <div class="extra">
              <span>单位（职务）：</span>
              <span
                >填表日期：{{ parseTime(new Date(), "{y}年{m}月{d}日") }}</span
              >
            </div>
          </div>
          <weekly-report-table
            :dataSource="weeklyReportDatas"
            :planType="planType"
            :columnNames="columnNames"
            :onAdd="handleAddRecord"
            :onDelete="handleDeleteRecord"
            :onSubmit="handleSaveRecord"
          />
        </el-card>
    <!-- 选择领导 -->
    <el-dialog
      title="选择人员"
      :visible.sync="dialogSelectUser"
      append-to-body
      :modal="false"
      width="90%"
      style="margin-top: -6vh"
    >
       <user-manager
        :isRadio="true"
        :userOuter="false"
        :onSelectUsers="handSelectLeader"
        ref="userManager"
      />
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import _ from 'lodash'
import moment from 'moment'
import { uuid, parseTime } from "@/utils/index.js";
import { createWeekSchedule } from "@/api/plann";

export default {
  props: {
    weekRecords: {
      type: Array,
      default: () => [],
    },
    date: {
      type: String,
    },
    planType: {
      type: String,
    },
    onClose: {
      type: Function,
    },
  },
  computed: {
    ...mapGetters(["name", "id","roles"]),
    tableTitle() {
      if (this.planType === "周") {
        const week = moment(this.date).week();
        return '第' +  week + "周重点工作事项表";
      }
      const month = moment(this.date).month() + 1;
      return '第' +  month + "月重点工作自评表";
    },
    // 当前用户是否是特殊用户
    isSpecialLeader() {
      return this.roles.includes('特殊领导')
    }
  },
  components: {
    WeeklyReportTable: () => import("./WeeklyReportTable.vue"),
    UserManager: () =>
      import("@/views/markSys/taskCenter/components/userManager.vue"),
    CurrentMonthWeekPlan: () => import("./CurrentMonthWeekPlan.vue")
  },
  watch: {
    weekRecords: {
      handler(records) {
        this.saveOwnerRecord(this.weekRecords, this.id);
        this.selectedUser = {
          username: this.name && this.name.split("(")[0],
          user: this.id,
        };
        this.tbr = null
        this.tbrPhone = null
      },
      immediate: true,
    },
    planType: {
      handler(type) {
        if (type === "月") {
          this.weeklyReportDatas = [this.initRecord()];
        }
      },
      immediate: true,
    },
  },

  data() {
    return {
      weeklyReportDatas: [this.initRecord()],
      dialogSelectUser: false,
      selectedUser: {},
      isRandomCheck: 0,
      columnNames: ["本周工作完成情况", "下周重点工作安排"],
      currentMonthTemp: "工作事项：\n工作亮点：\n",
      nextMonthTemp: "工作事项：\n主要原因：\n整改措施：\n",
      classifyWrapper: {sm: 24, md: 24, lg: 6},
      tbr:'',
      tbrPhone:'',
      dataListForTbrPhone:[],
      dataListForTbr:[],

    };
  },
  mounted(){
    this.dataListForTbrPhone = JSON.parse(localStorage.getItem("dataListForTbrPhone"));
    this.dataListForTbr = JSON.parse(localStorage.getItem("dataListForTbr"));
  },
  methods: {
    handChangeTbr(){
      this.dataListForTbr = JSON.parse(localStorage.getItem("dataListForTbr"));
    },
    handChangePhone(){
      this.dataListForTbrPhone = JSON.parse(localStorage.getItem("dataListForTbrPhone"));
    },
    parseTime,
    initRecord() {
      return {
        tempID: "new" + uuid(),
        current_week: this.planType === "周" ? "" : this.currentMonthTemp,
        next_week: this.planType === "周" ? "" : this.nextMonthTemp,
      };
    },
    handSelectLeader(users) {
      if (!users.length) {
        this.$message.info("请选择处理人");
        return;
      }
      const { first_name, id } = users[0];

      this.selectedUser = { username: first_name, user: id };
      this.dialogSelectUser = false;
      this.saveOwnerRecord(this.weekRecords, id);
    },
    saveOwnerRecord(records, user) {
      let list = [];
      // 过滤属于选择人员的记录
      const ownerRecords = records.filter((item) => item.user_id == user) || [];
      if (ownerRecords.length) {
        // 转换为指定格式
        list = ownerRecords.map((item) => {
          const { content, seven_day } = item;
          return {
            tempID: "new" + uuid(),
            current_week: content,
            next_week: seven_day,
          };
        });
      } else {
        // 初始化
        list = [this.initRecord()];
      }

      this.weeklyReportDatas = list;
    },
    handleAddRecord() {
      this.weeklyReportDatas.push(this.initRecord());
    },
    handleDeleteRecord(selectedRows) {
      const rowsId = selectedRows.map((item) => item.tempID);
      const filterList = this.weeklyReportDatas.filter(
        (item) => !rowsId.includes(item.tempID)
      );
      this.weeklyReportDatas = filterList.length
        ? filterList
        : [this.initRecord()];
    },
    /*
     * 缓存输入框记录
     * param: String; 对象字段名称
     */
    saveInputSessionForDataListForTbr(param) {
      const value = param;
      if (!value) return;
      var locData = JSON.parse(localStorage.getItem("dataListForTbr"));
      if (!locData || !locData.includes(value)) {
        if (!locData) {
          localStorage.setItem("dataListForTbr", JSON.stringify([value]));
        } else {
          if (locData.length > 4) {
            locData = locData.slice(locData.length - 4, locData.length);
          }
          localStorage.setItem(
            "dataListForTbr",
            JSON.stringify(locData.concat([value]))
          );
        }
      }
    },
    /*
     * 缓存输入框记录
     * param: String; 对象字段名称
     */
    saveInputSessionForDataListForTbrPhone(param) {
      const value = param;
      if (!value) return;
      var locData = JSON.parse(localStorage.getItem("dataListForTbrPhone"));
      if (!locData || !locData.includes(value)) {
        if (!locData) {
          localStorage.setItem("dataListForTbrPhone", JSON.stringify([value]));
        } else {
          if (locData.length > 4) {
            locData = locData.slice(locData.length - 4, locData.length);
          }
          localStorage.setItem(
            "dataListForTbrPhone",
            JSON.stringify(locData.concat([value]))
          );
        }
      }
    },
    handleSaveRecord: _.debounce(async function() {
      this.saveInputSessionForDataListForTbr(this.tbr)
      this.saveInputSessionForDataListForTbrPhone(this.tbrPhone)
      // 周报、月报都已报告日期为主
      let weekOrMonth = moment(this.date).format("YYYY-MM-DD");
      // if (this.planType === "周") {
      //   weekOrMonth = moment(this.date).format("YYYY-MM-DD");
      // } else {
      //   weekOrMonth = moment(new Date()).format("YYYY-MM-DD");
      // }
      const { user } = this.selectedUser;
      const newRows = [...this.weeklyReportDatas];
      const isEmpty = newRows.some((item) => !item.current_week);
      if (isEmpty) {
        this.$message.info("本周重点工作安排不能为空");
        return;
      }
      const _newRows = newRows.map((row) => {
        return { ...row, week_date: weekOrMonth, type: this.planType, user, range_inspect: this.isRandomCheck, tbr: this.tbr, tbr_phone: this.tbrPhone };
      });
      
      createWeekSchedule(_newRows).then((res) => {
        if (res && res.data) {
          this.$message.success("保存成功");
          this.onClose();
          this.weeklyReportDatas = [this.initRecord()];
        }
      });
    }, 300
    ),
    handleDialogSelectUser(){
      if(this.roles.some(role => ~role.indexOf('管理员'))){
        this.dialogSelectUser = true
      }
    }
  },
};
</script>
<style lang="scss">
.weekly-report-form {
  margin-top: -20px;
  .person {
    margin-bottom: 20px;
    line-height: 20px;
    font-size: 13px;
    color: #232323;
    cursor: pointer;
    div:last-child > span{
      margin-left: 20px;
    }
    .icon {
      font-size: 18px;
      vertical-align: top;
      color: #409EFF;
    }
    .top-input{
      width: 200px;
      input{
        height: 26px;
        padding-right: 0 !important;
        line-height: 14px;
      }
    }
    .importBtn {
      float: right;
      margin-top: 5px;
      font-size: 12px;
      color: #409eff;
      cursor: pointer;
    }
  }
  .box-card {
    margin-bottom: 20px;
    .header {
      h2 {
        text-align: center;
        color: #666;
      }
      .extra {
        margin-top: 34px;
        padding: 0 40px 4px 13px;
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #ebeef5;
        font-size: 14px;
        color: #666;
      }
    }
  }
  @media screen and (max-width: 500px){ 
    .box-card {
      .el-card__body {
        padding: 20px 10px;
      }
    }
    .person{
      div:last-child{
        display: block !important;
        margin-top: 4px ;
        span{
          margin-left: 0px !important;
          display: block;
          div{
            display: inline-block !important;
          }
        }
        span:last-child{
          margin-top: 4px;
        }
      }
    }
  }
}
</style>